<?php

namespace app\common\model\xiservice;

use app\common\model\xiservice\Benfit as BenfitModel;
use app\common\model\xiservice\Comment as CommentModel;
use app\common\model\xiservice\Schedule as ScheduleModel;
use app\common\model\xiservice\User as XiserviceUser;
use think\Db;
use think\Exception;
use think\Model;


class DepositOrder extends Model
{


    // 表名
    protected $name = 'xiservice_deposit_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_status_text',
        'type_text'
    ];


    public function getPayStatusList()
    {
        return ['10' => __('Pay_status 10'), '20' => __('Pay_status 20')];
    }



    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }


    public function changeOrderStatus($id, $status)
    {

        $orderInfo = $this->where('id', $id)->find();
        if (!$orderInfo) {
            return ['status' => false, "data" => [], 'msg' => '订单不存在'];
        }


        //订单付款判断
        if ($status == 'payed' && $orderInfo['pay_status'] == '20') {
            return ['status' => false, "data" => [], 'msg' => '订单已支付'];
        }

        Db::startTrans();
        $nowTime = time();
        $date = date('Y-m-d', $nowTime);
        $orderSaveData = [];
        try {
            switch ($status) {

                case 'payed'://付款
                    $orderSaveData['pay_status'] = '20';
                    break;

                default:
                    break;
            }

            //更新状态
            $resv = $this->save($orderSaveData, ["id" => $id]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        } catch (\InvalidArgumentException $e) {
            Db::rollback();
            return ["status" => false, "data" => [], "msg" => $e->getMessage()];
        }

        return ["status" => true, "data" => [], "msg" => "操作成功"];
    }
}
